﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Domain;
using System.Data;
using Data.ViewModels;

namespace Data.Repositories
{
    public class PerguntaRepository
    {
        ModeloCantinhoContainer db = new ModeloCantinhoContainer();

        public IEnumerable<Question> GetAll()
        {
            return db.Question.Include("User");
        }

        public IEnumerable<PerguntaViewModel> GetAllViewModel(int page, int size, out int total)
        {
            int skip = size * page;
            skip -= size;
            total = db.Question.Count();

            IEnumerable<PerguntaViewModel> View = (from x in db.Question.Include("User")
                         select new PerguntaViewModel {
                         Answers = x.Answer.Count,
                         LastUpdateDate = x.Answer.Count > 0 ? x.Answer.OrderByDescending(z=>z.DateCreated).FirstOrDefault().DateCreated : x.DateCreated,
                         LastUpdateUser = x.Answer.Count > 0? x.Answer.OrderByDescending(z=>z.DateCreated).FirstOrDefault().User : x.User,
                         Title = x.Title,
                         Views = x.Views,
                         Votes = x.Votes,
                         Id = x.Id,
                         Body = x.Body,
                         Tags = x.Tag
                         }).OrderByDescending(c=>c.Votes).ThenByDescending(c=>c.Answers).ThenByDescending(c => c.LastUpdateDate).Skip(skip).Take(size);

            return View;
        }

        public Question GetById(int id, bool updateviews)
        {
            Question question = db.Question.Single(q => q.Id == id);
             //incrementar o numero de views
            if (updateviews)
            {
                question.Views += 1;
                Update(question);
            }
            return question;
        }

        public Question GetByNome(string nome, bool updateviews)
        {
            Question question = db.Question.Single(q => q.Title == nome);
            //incrementar o numero de views
            if (updateviews)
            {
                question.Views += 1;
                Update(question);
            }
            return question;
        }

        public int Votar(int id, int accao,string email)
        {
            Question a = GetById(id,false);
            if (a == null) return -10000;

            UserRepository repUser = new UserRepository();

            if(a.User.Id == repUser.GetUserByEmail_Aprovado(email).Id)
                return -10001;

            if (accao == 0) //Descer voto
            {
                a.Votes -= 1;
                //Grava pontos    
                repUser.GravaPontos(PontosRepository.TipoPonto.PerguntaVotoNegativo, a.User);
            }
            else //Subir voto
            {
                a.Votes += 1;
                //Grava pontos    
                repUser.GravaPontos(PontosRepository.TipoPonto.PerguntaVotoPositivo, a.User);
            }
            Update(a);

            return a.Votes;
        }

        public void Create(Question question,string email,string tags,string avisar)
        {
            question.DateCreated = DateTime.Now;
            UserRepository rep = new UserRepository();
            User user = rep.GetUserByEmail_Aprovado(email);
            question.UserId = user.Id;

            rep.GravaPontos(PontosRepository.TipoPonto.Pergunta, user);

            if (!string.IsNullOrEmpty(avisar) && avisar == "on")
            {
                //colocar email na lista de avisos desta pergunta
            }

            string[] Tags = tags.Split(',');
            
            foreach (string tag in Tags)
	        {
                question.Tag.Add(new Tag { TagName = tag });
	        }

            db.Question.AddObject(question);
            db.SaveChanges();
        }

        public void Update(Question question)
        {
            try
            {
                db.Question.Attach(question); db.ObjectStateManager.ChangeObjectState(question, EntityState.Modified);
            }
            catch (Exception)
            {
            }
            finally
            {
               
                db.SaveChanges();
            }
        }

        public void Delete(int id)
        {
            Question question = db.Question.Single(q => q.Id == id);
            db.Question.DeleteObject(question);
            db.SaveChanges();
        }

        public IEnumerable<Question> GetAllByTag(string id)
        {
            
            //return  from c in db.Tag
            //        where c.TagName == id
            //        select c.Question.AsEnumerable<Question>();
            return null;
   
        }
    }
}
